#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cre2.h>

#define PRINTF(...) { printf(__VA_ARGS__);         fflush(stdout); }
#define FWRITE(...) { fwrite(__VA_ARGS__, stdout); fflush(stdout); }

int main (void)
{
    const char *pattern;
    const char *text;

    /* 单一匹配 */
    pattern = "ciao";
    text    = "ciao hello";
    {
        cre2_string_t match;
        int nmatch = 1;
        cre2_easy_match(pattern, strlen(pattern),
                        text, strlen(text),
                        &match, nmatch);
        PRINTF("single match: ");
        FWRITE(match.data, match.length, 1);
        PRINTF("\n");
    }

    /* 错误匹配 */
    pattern = "ci(ao";
    text    = "ciao";
    {
        cre2_string_t match;
        int nmatch = 1;
        int retval;
        retval = cre2_easy_match(pattern, strlen(pattern),
                                 text, strlen(text),
                                 &match, nmatch);
        PRINTF("error pattern ret = %d\n", retval);

        if (2 != retval)
            goto error;
    }

    /* 两个分组 */
    pattern = "(ciao) (hello)";
    text    = "ciao hello world";
    {
        int nmatch = 3;
        cre2_string_t match[nmatch];
        cre2_easy_match(pattern, strlen(pattern),
                        text, strlen(text),
                        match, nmatch);

        PRINTF("two groups: \n");
        PRINTF("whole match(group 0): ");
        FWRITE(match[0].data, match[0].length, 1);
        PRINTF("\n");
        PRINTF("first group: ");
        FWRITE(match[1].data, match[1].length, 1);
        PRINTF("\n");
        PRINTF("second group: ");
        FWRITE(match[2].data, match[2].length, 1);
        PRINTF("\n");
    }

    exit(EXIT_SUCCESS);
error:
    exit(EXIT_FAILURE);
}
